import datetime
import time
import requests
from Model.Sensor import *
from DAO.HDataDAO import *

def get_data():
    url = "http://172.21.21.14:8103/prod-api/largeScreen/queryLargeScreenTemperatureAndHumidity?idcId=89313d16-2223-11ef-93ec-0242ac110005"
    headers = {
        "Cookie": "JSESSIONID=77C27E4F3F97EBB29EBBF65EB9E4AD4C; vue_admin_template_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJwYXNzd29yZCI6ImFkbWluQDEyMyIsInVzZXJuYW1lIjoiYWRtaW4ifQ.yILvN2N_XL_BmGPiwtN3HmrAXgOxaRLLhjO0fO8lp2k",
        "User-Agent": "apifox/1.0.0 (https://www.apifox.cn)",
        "Accept": "*/*",
        "Host": "172.21.21.14:8103",
        "Accept-Encoding": "gzip, deflate, br",
        "Connection": "keep-alive"
    }

    while True:
        try:
            response = requests.post(url, headers=headers)
            data = response.json()
            return data
        except Exception as e:
            print(f"出现错误：{e}，60 秒后重试。")
            time.sleep(60)
    return data

def save_into_db():
    data = get_data()
    sensor_obj = Sensor(data['data'], datetime.datetime.now())  # 为 Sensor 类提供当前时间作为 time 参数
    sensor_dict = sensor_obj.to_dict()
    # print(sensor_dict)
    s_db = SensorDateDAO()
    s_db.insert_one(sensor_dict)

    # 均值计算
    directions = ['北', '东', '南', '西']
    averages = {}

    for direction in directions:
        humidity_avg, temperature_avg = calculate_average(data, direction)
        averages[direction] = (humidity_avg, temperature_avg)
    
    sensor_direction_obj = SensorDirection(averages, datetime.datetime.now())  # 为 Sensor 类提供当前时间作为 time 参数
    sensor_direction_dict = sensor_direction_obj.to_dict()
    s_d_db = SensorDirectionDateDAO()
    s_d_db.insert_one(sensor_direction_dict)

    
def calculate_average(data, direction):
    humidity_sum = 0
    temperature_sum = 0
    count = 0

    for item in data['data']:
        if item['device_name'].startswith(f'6F-{direction}'):
            humidity = float(item['humidityValue'][:-1])
            temperature = float(item['temperatureValue'][:-2])
            humidity_sum += humidity
            temperature_sum += temperature
            count += 1

    # for item in data['data']:
    #     if item['device_name'].startswith(f'5F-{direction}'):
    #         humidity = float(item['humidityValue'][:-1])
    #         temperature = float(item['temperatureValue'][:-2])
    #         humidity_sum += humidity
    #         temperature_sum += temperature
    #         count += 1
    
    # for item in data['data']:
    #     if item['device_name'].startswith(f'4F-{direction}'):
    #         humidity = float(item['humidityValue'][:-1])
    #         temperature = float(item['temperatureValue'][:-2])
    #         humidity_sum += humidity
    #         temperature_sum += temperature
    #         count += 1

    if count == 0:
        return 0, 0

    return humidity_sum / count, temperature_sum / count

if __name__ == '__main__':
    print(get_data()) 